package utils

import (
	"crypto/rand"
	"math/big"

	"golang.org/x/crypto/bcrypt"
)

const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

// RandomSalt 随机盐值
func RandomSalt(length int) string {

	// 创建一个字节切片，长度为需要的盐值长度
	salt := make([]byte, length)

	charsetLength := big.NewInt(int64(len(charset)))

	for i := range salt {
		// 随机选择一个字符
		randomCharIndex, err := rand.Int(rand.Reader, charsetLength)
		if err != nil {
			return "123456"
		}
		salt[i] = charset[randomCharIndex.Int64()]
	}

	return string(salt)
}

// GeneratePassword 生成密码
func GeneratePassword(passwd string) (string, string) {
	salt := RandomSalt(6)
	return GeneratePasswordWithSlat(passwd, salt), salt
}

// GeneratePasswordWithSlat 带盐的密码
func GeneratePasswordWithSlat(passwd, salt string) string {
	target, _ := bcrypt.GenerateFromPassword([]byte(passwd+salt), bcrypt.MinCost)
	return string(target)
}

// VerifyPassword 验证密码
func VerifyPassword(ciphertext, password string) bool {
	return bcrypt.CompareHashAndPassword([]byte(ciphertext), []byte(password)) == nil
}
